// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

package com.netease.yunxin.kit.chatkit.ui.page.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import androidx.lifecycle.ViewModelProvider;

import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luoxiang.lib_common.bean.NumberBean;
import com.luoxiang.lib_common.utils.AESUtil;
import com.luoxiang.lib_common.utils.MmkvUtil;
import com.luoxiang.lib_common.utils.NetUtils;
import com.lxj.xpopup.XPopup;
import com.netease.nim.highavailable.LogUtils;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.yunxin.kit.alog.ALog;
import com.netease.yunxin.kit.chatkit.ui.R;
import com.netease.yunxin.kit.chatkit.ui.bean.BlockBean;
import com.netease.yunxin.kit.chatkit.ui.common.MessageHelper;
import com.netease.yunxin.kit.chatkit.ui.page.ChatSettingActivity;
import com.netease.yunxin.kit.chatkit.ui.page.viewmodel.ChatP2PViewModel;
import com.netease.yunxin.kit.common.ui.utils.ToastUtils;
import com.netease.yunxin.kit.common.ui.viewmodel.LoadStatus;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * P2P chat page
 */
public class ChatP2PFragment extends ChatBaseFragment {
    private static final String TAG = "ChatP2PFragment";
    private String account;
    private static final int TYPE_DELAY_TIME = 3000;

    UserInfo userInfo;

    String accId;

    private int block;

    private String shielding = "拉黑";

    private final Handler handler = new Handler();

    private final Runnable stopTypingRunnable = () -> binding.chatView.setTypeState(false);

    @Override
    protected void initData(Bundle bundle) {
        ALog.i(TAG, "initData");
        sessionType = SessionTypeEnum.P2P;
        userInfo = (UserInfo) bundle.getSerializable(RouterConstant.CHAT_KRY);
        accId = (String) bundle.getSerializable(RouterConstant.CHAT_ID_KRY);
        if (userInfo != null) {
            account = userInfo.getAccount();
            LogUtils.i("accounttouserid", account);
        }
        //对方IMid
        if (account != null) {
            MmkvUtil.INSTANCE.encode("accidtouser", account);//拿到对方的accid
        } else if (accId != null) {
            MmkvUtil.INSTANCE.encode("accidtouser", accId);//拿到对方的accid
        } else {
            ToastUtils.INSTANCE.showShortToast(requireActivity(), "未获取到id");
        }
        if (userInfo == null && TextUtils.isEmpty(accId)) {
            getActivity().finish();
            return;
        }
        if (TextUtils.isEmpty(accId)) {
            accId = userInfo.getAccount();
        }
        binding
                .chatView
                .getTitleBar()
                .setOnBackIconClickListener(v -> requireActivity().onBackPressed())
                .setActionImg(R.drawable.ic_more_point)
                .setActionListener(
                        v -> {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), ChatSettingActivity.class);
                            intent.putExtra(RouterConstant.CHAT_ID_KRY, accId);
                            startActivity(intent);
                        });
        refreshView();
        binding.chatView.getTitleBar().setActionImg(R.drawable.icon_touming);
        binding.chatView.getTitleBar().setActionListener(view -> {
            //对于右上角按钮不做任何操作
        });
        getBlock(EXTRA, MmkvUtil.INSTANCE.decodeString(TOKEN), Integer.parseInt(accId));
    }

    private void refreshView() {
        String name = MessageHelper.getUserNickByAccId(accId, userInfo, false);
        binding.chatView.getTitleBar().setTitle(name);
        binding.chatView.getInputView().updateInputInfo(name);
    }


    @Override
    protected void initViewModel() {
        ALog.i(TAG, "initViewModel");
        viewModel = new ViewModelProvider(this).get(ChatP2PViewModel.class);
        viewModel.init(accId, SessionTypeEnum.P2P);
        //fetch history message
        viewModel.initFetch(null);
        ((ChatP2PViewModel) viewModel).getP2pUserInfo(accId);
        binding.chatView.getTitleBar().setActionImg(R.drawable.icon_fenxiang_24_000_nor);
        binding.chatView.getTitleBar().setActionListener(v -> {
            new XPopup.Builder(getContext())
                    .atView(v)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                    .asAttachList(new String[]{"查看主页", "举报", shielding, "取消"},
                            null,
                            (position, text) -> {
                                switch (position) {
                                    case 0:
                                        LiveEventBus.<String>get("startDetailsActivity").post(accId);
                                        break;
                                    case 1:
                                        LiveEventBus.<Integer>get("startReportActivity").post(Integer.valueOf(accId));
                                        break;
                                    case 2:
                                        if (block == 0) {
                                            block = 1;
                                        } else {
                                            block = 0;
                                        }
                                        getBlocktorf(EXTRA, MmkvUtil.INSTANCE.decodeString(TOKEN), Integer.parseInt(accId), block);
                                        break;
                                    case 3:
                                        break;
                                }
                            })
                    .show();
        });
    }

    /**
     * 拉黑/取消拉黑
     */
    private void getBlocktorf(String extra, String token, int toUserId, int block) {
        NetUtils.getInstance().getApiService().getImblock(extra, token, toUserId, block)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr42", decryptStr);
                        getBlock(EXTRA, token, toUserId);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取拉黑状态
     *
     * @param extra
     * @param token
     * @param toUserId
     */
    private void getBlock(String extra, String token, int toUserId) {
        NetUtils.getInstance().getApiService().getBlock(extra, token, toUserId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr41", decryptStr);
                        Gson gson = new Gson();
                        BlockBean bean = gson.fromJson(decryptStr, BlockBean.class);
                        if (bean != null) {
                            if (bean.getData() != null) {
                                block = bean.getData().getBlock();
                                if (block == 0) {
                                    shielding = "拉黑";
                                } else {
                                    shielding = "取消拉黑";
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    protected void initDataObserver() {
        super.initDataObserver();
        ALog.i(TAG, "initDataObserver");
        ((ChatP2PViewModel) viewModel)
                .getMessageReceiptLiveData()
                .observe(
                        getViewLifecycleOwner(),
                        imMessageReceiptInfo ->
                                binding
                                        .chatView
                                        .getMessageListView()
                                        .setP2PReceipt(imMessageReceiptInfo.getMessageReceipt().getTime()));

        ((ChatP2PViewModel) viewModel)
                .getTypeStateLiveData()
                .observe(
                        getViewLifecycleOwner(),
                        isTyping -> {
                            handler.removeCallbacks(stopTypingRunnable);
                            binding.chatView.setTypeState(isTyping);
                            if (isTyping) {
                                handler.postDelayed(stopTypingRunnable, TYPE_DELAY_TIME);
                            }
                        });
        ((ChatP2PViewModel) viewModel)
                .getP2pUserInfoLiveData()
                .observe(
                        getViewLifecycleOwner(),
                        result -> {
                            if (result.getLoadStatus() == LoadStatus.Success) {
                                userInfo = result.getData();
                                refreshView();
                            }
                        });
    }
}
